#include "serialui.h"
#include "ui_serialui.h"
#include <QTimer>

SerialUI::SerialUI(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SerialUI)
{
    ui->setupUi(this);
    tableDialog = new TableDialog(this);
    connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &SerialUI::onOkClicked);
    // 移除问号按钮
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    // 初始化串口下拉框
    updateSerialPorts();
}

SerialUI::~SerialUI()
{   if (m_thread) {
        m_thread->quit();
        m_thread->wait();
        delete m_thread;
    }
    delete ui;
    delete m_serialPort;
    delete m_serialParser;
    delete tableDialog;
    
}
// 当点击 OK 按钮时，发射串口配置信号
void SerialUI::onOkClicked()
{
    // 创建 QSettings 对象，指定存储为 INI 格式的 config.ini 文件
    QSettings settings("config.ini", QSettings::IniFormat);
    
    settings.beginGroup("Serial");

    // 保存各项配置信息
    settings.setValue("PortName", ui->comBox_uartPort->currentText());
    settings.setValue("BaudRate", ui->comBox_uartDps->currentText().toInt());
    settings.setValue("DataBits", ui->comBox_uartDataLen->currentText().toInt());
    settings.setValue("Parity", ui->comBox_uartCheckBit->currentIndex());
    settings.setValue("StopBits", ui->comBox_uartStopBit->currentText().toInt());
    settings.setValue("FlowControl", ui->comBox_uartFlowControl->currentText());

    // 结束配置组
    settings.endGroup();
    // 关闭对话框
    accept();
}
void SerialUI::updateSerialPorts()
{
    ui->comBox_uartPort->clear(); // 清空当前的串口列表

        // 获取所有可用串口
        const QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts();

        for (const QSerialPortInfo &portInfo : ports) {
            ui->comBox_uartPort->addItem(portInfo.portName()); // 添加可用串口到下拉框
        }

        // 如果没有可用串口，添加提示信息
        if (ui->comBox_uartPort->count() == 0) {
            ui->comBox_uartPort->addItem("No available ports");
            QMessageBox::warning(this, "Warning", "No serial ports found. Please check your hardware connection.");
        } else {
            ui->comBox_uartPort->setCurrentIndex(0); // 默认选择第一个可用的串口
        }
}
void SerialUI::startThread() {
//    if (m_thread) {
//        QMessageBox::warning(this, "Warning", "Serial thread already running.");
//        return;
//    }

    // 初始化串口对象、解析器和线程
    m_serialPort = new QSerialPort(this);
    m_serialParser = new serialparser();
    // 设置串口参数
    QSettings settings("config.ini", QSettings::IniFormat);
    m_serialPort->setPortName(settings.value("Serial/PortName").toString());
    m_serialPort->setBaudRate(settings.value("Serial/BaudRate").toInt());
    m_serialPort->setDataBits(QSerialPort::DataBits(settings.value("Serial/DataBits").toInt()));
    m_serialPort->setParity(QSerialPort::Parity(settings.value("Serial/Parity").toInt()));
    m_serialPort->setStopBits(QSerialPort::StopBits(settings.value("Serial/StopBits").toInt()));

    // 将解析器移动到线程
    m_thread = new QThread(this);
    m_serialParser->moveToThread(m_thread);

    // 绑定信号与槽
   connect(this, &SerialUI::rawSerialDataReceived, m_serialParser, &serialparser::processData); // 绑定信号到槽
   connect(m_serialParser, &serialparser::parsedDataReady, this, &SerialUI::onDataParsed); // 解析完成后的槽

   // 连接线程的生命周期信号
   connect(m_thread, &QThread::started, this, &SerialUI::onThreadStarted);
   connect(m_thread, &QThread::finished, this, &SerialUI::onThreadFinished);

   // 启动线程
   m_thread->start();
   emit threadStatusChanged(true); // 通知按钮线程已启动
}
//
void SerialUI::onThreadStarted() {
    if (!m_serialPort->open(QIODevice::ReadOnly)) {
        qDebug() << "Serial port error:" << m_serialPort->errorString();
        QMessageBox::critical(this, "Error", "Failed to open serial port.");
        emit threadStatusChanged(false); // 通知按钮更新状态
        m_thread->quit();
        return;
    }

    // 监听串口数据
    connect(m_serialPort, &QSerialPort::readyRead, this, [this]() {
        QByteArray rawData = m_serialPort->readAll();
        emit rawSerialDataReceived(QString::fromUtf8(rawData));
    });

}
//表格数据显示
void SerialUI::onDataParsed(const QString &parsedData) {
     qDebug() << "Displaying parsed data:" << parsedData; // 调试输出
     QStringList parsedFields = parsedData.split("\n");
     tableDialog->addData(parsedFields); // 添加数据到表格

}

void SerialUI::onThreadFinished() {
    if (m_serialPort) {
        if (m_serialPort->isOpen()) {
            m_serialPort->close();
        }
        delete m_serialPort;
        m_serialPort = nullptr;
    }

    if (m_serialParser) {
        delete m_serialParser;
        m_serialParser = nullptr;
    }

    if (m_thread) {
        delete m_thread;
        m_thread = nullptr;
    }

    qDebug() << "Thread finished and resources cleaned up.";
}


void SerialUI::stopThread() {
    if (!m_thread) {
        QMessageBox::warning(this, "Warning", "No serial thread is running.");
        return;
    }

    qDebug() << "Stopping serial thread.";

    // 停止线程
    m_thread->quit();
    m_thread->wait();

    // 确保串口关闭
    if (m_serialPort && m_serialPort->isOpen()) {
        m_serialPort->close();
    }

    // 清理资源
    delete m_serialPort;
    m_serialPort = nullptr;

    delete m_serialParser;
    m_serialParser = nullptr;

    delete m_thread;
    m_thread = nullptr;
    emit threadStatusChanged(false); // 通知按钮线程已停止
    QMessageBox::information(this, "Info", "Serial thread stopped.");
    qDebug() << "Serial thread stopped successfully.";
}
void SerialUI::showTableView()
{   tableDialog->clearData();
    if (tableDialog) {
        tableDialog->show();  // 显示表格对话框
        tableDialog->raise(); // 确保窗口在最前方
    } else {
        QMessageBox::warning(this, "Warning", "Table dialog is not initialized.");
    }
}
